import {slugify} from 'transliteration';
import base from "./base.controller";


export default class extends base {

    async _initialize() {
        await super._initialize();
    }

    async index() {
        await this.render('admin/comment/index', {
            status: [{key: '0', title: '关闭'}, {key: '1', title: '开启'}]
        });
    }

    async update() {

        const id = this.query.id;
        const status = this.query.status;
        const ids = id.split(',');

        for (let i in ids) {
            await this.model('admin/Comment').add({id: ids[i], status: status});
        }

        this.json('/admin/comment/index', '保存成功');
    }

    async table() {

        const p = this.query.page || 1;

        const post = this.post;
        const id = post.id.trim();
        const status = post.status.trim();
        const keywords = post.keywords.trim();

        //构造查询条件
        let queryParams = {};

        //正则表达式查询
        if (keywords !== "") {
            queryParams = {
                $or: [
                    {title: {$regex: keywords, $options: "$i"}},
                    // {email: {$regex: keywords, $options: "$i"}},
                    // {mobile: {$regex: keywords, $options: "$i"}}
                ]
            }
        }

        //等值查询
        if (status !== "") {
            queryParams = Object.assign(queryParams, {status: status});
        }

        //id属性要单独查找,不支持正则表达式
        if (id !== "") {
            try {
                queryParams = {
                    _id: koahub.mongoose.Types.ObjectId(id)
                }
            } catch (err) {
                this.error('没找到符合条件的记录');
                return;
            }
        }


        // this.logger.debug(`search queryParams:${JSON.stringify(queryParams)}`);
        const pageSize= await this.common.config('LIST_ROWS');
        let pageEntity = await this.model('admin/Comment').findPage({
            page: p,
            pageSize: pageSize
        }, 'commenter', queryParams, {}, {createdAt: 'asc'}, function (error, results) {

        });

        // this.logger.debug(pageEntity);
        await this.render('admin/comment/table', {
            records: pageEntity.data,
            pager: this.common.ajaxPage(p, pageEntity.pagination.rowCount, pageEntity.pagination.pageSize)
        });
    }

    async disable() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Comment');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 0}).exec();
        }
        this.success('/admin/comment/index','禁用评论成功');

    }

    async enable() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Comment');
        for (const i of ids) {
            await Model.findByIdAndUpdate(i, {status: 1}).exec();
            //this.changeModelField('admin/admin/Administrator', i, 'status', 1);
        }
        this.success('/admin/comment/index','恢复成功');
    }

    async delete() {
        const id = this.post.id || "";
        const ids = id.split(',');
        let Model = this.model('admin/Comment');
        const CommentModel=this.model('admin/Comment');
        for (const i of ids) {
            await CommentModel.remove({
                rowId:i,
            });

            await Model.findByIdAndRemove(i).exec();
        }
        this.success('/admin/comment/index', '删除评论成功');
    }

    async add() {

        if (this.isPost()) {

            const comment = this.post;

            comment.pinyin = slugify(comment.title);

            await this.model('admin/Comment').saveOrUpdate(comment);

            this.json('/admin/comment/index', '保存成功');
        } else {

            if (this.query.id) {
                //查出关联的封面图片信息
                const comment = await this.model('admin/Comment').findOne({_id: this.query.id}).populate('cover');
                if (comment) {
                    await this.render('admin/comment/add', {comment: comment});
                } else {
                    this.logger.warn(`文章${this.query.id}不存在`);
                    this.redirect('/admin/comment/index?err=' + encodeURI('文章不存在'));
                }
            } else {
                await this.render('admin/comment/add');
            }
        }
    }
}
